<template>
  <el-dialog
      :title="props.type === 'add' ? '新增用户' : '编辑用户'"
      v-model="state.visible"
      width="400px"
  >
    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
      <el-form-item label="账号" prop="username">
        <el-input type="text" :disabled="isDisable()" v-model="state.ruleForm.username"></el-input>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input type="text" v-model="state.ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input type="text" v-model="state.ruleForm.phone"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input type="text" v-model="state.ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
            :action="uploadImgServer"
            :on-success="handleUrlSuccess"
            list-type="picture"
            :auto-upload="true"
            :show-file-list="false"
        >
          <img v-if="state.ruleForm.avatar" :src="state.ruleForm.avatar" class="cover" alt="封面"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import {addNursingHome, updateNursingHome, getNursingHomeById} from '../service/nursingHomeApi.js'
import {uploadImgServer} from "../store/index.js"
import {ElMessage} from 'element-plus'
import {adduser, getUserById, updateUser} from "../service/userApi.js";

const props = defineProps({
  type: String, // 用于判断是添加还是编辑
  reload: Function // 添加或修改完后，刷新列表页
})
const formRef = ref(null)
const route = useRoute()
const state = reactive({
  visible: false,
  categoryLevel: 1,
  parentId: 0,
  ruleForm: {
    id: '',
    name: '',
    password: '',
    phone: '',
    username: '',
    avatar: '',
    role: '',
    email: ''
  },
  rules: {
    username: [
      {required: true, message: '用户账号不能为空', trigger: ['change']}
    ],
    name: [
      {required: true, message: '姓名不能为空', trigger: ['change']}
    ],
    avatar: [
      {required: true, message: '头像不能为空', trigger: ['change']}
    ]
  },
})
const isDisable = () => {
  return props.type === 'edit'
}
// 获取详情
const getDetail = async (id) => {
  const result = await getUserById(id);
  // 回显表单数据
  state.ruleForm = {
    id: result.data.id,
    name: result.data.name,
    avatar: result.data.avatar,
    phone: result.data.phone,
    username: result.data.username,
    email: result.data.email,
    role: result.data.role
  }
}

//上传成功
const handleUrlSuccess = (res) => {
  state.ruleForm.avatar = res.data
}

// 开启弹窗
const open = (id) => {
  state.visible = true
  if (id) {
    state.ruleForm.id = id
    // 如果是有 id 传入，证明是修改模式
    getDetail(id)
  } else {
    // 否则为新增模式
    // 新增类目，从路由获取分类 level 级别和父分类 id
    const {level = 1, parent_id = 0} = route.query
    state.ruleForm = {
      id: '',
      name: '',
      password: '',
      phone: '',
      username: '',
      avatar: '',
      role: '',
      email: ''
    }
    state.parentId = parent_id
    state.categoryLevel = level
  }
}
// 关闭弹窗
const close = () => {
  state.visible = false
}
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type === 'add') {
        const params = {
          name: state.ruleForm.name,
          phone: state.ruleForm.phone,
          avatar: state.ruleForm.avatar,
          username: state.ruleForm.username,
          email: state.ruleForm.email,
          password: '123456',
        }
        // 添加方法
        await adduser(params).then(() => {
          ElMessage.success('添加成功')
          close()
          if (props.reload) props.reload()
        })
      } else {
        // 修改方法
        const params = {
          id: state.ruleForm.id,
          name: state.ruleForm.name,
          username: state.ruleForm.username,
          avatar: state.ruleForm.avatar,
          phone: state.ruleForm.phone,
          email: state.ruleForm.email,
          password: state.ruleForm.password,
          role: state.ruleForm.role
        }
        await updateUser(params).then(() => {
          ElMessage.success('修改成功')
          close()
          if (props.reload) props.reload()
        })
      }
    }
  })
}
defineExpose({open, close})
</script>

<style scoped>
.el-upload__tip {
  float: left;
}

.cover {
  border: 1px solid #1F3A5F;
  border-radius: 10px;
  width: 100px;
  height: 100px;
}
</style>